package com.hsh;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.filter.AbstractFilter;
import org.apache.logging.log4j.message.Message;


/**
 * @author: shaohai.huang
 * @date: 2020-03-26
 */
@Plugin(name = "CustomFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE, printObject = true)
public class CustomFilter extends AbstractFilter {

    public CustomFilter() {
        super(Result.ACCEPT, Result.ACCEPT);
    }

    @Override
    public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
                         final Throwable t) {
        zuesLog(level, msg, t);
        return Result.NEUTRAL;
    }

    @Override
    public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg,
                         final Throwable t) {
        zuesLog(level, msg, t);
        return Result.NEUTRAL;
    }

    @Override
    public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
                         final Object... params) {
        zuesLog(level, msg, null);
        return Result.NEUTRAL;
    }


    private void zuesLog(Level Level, Object msg, Throwable t) {
        /*try {
            int x = 1 / 0;
        } catch (Exception e) {
            throw new ZeusIdException();
        }*/
        RuntimeException zeusId = new RuntimeException("zeusid-11111");
        if (t != null) {
            if (t.getCause() == null) {
                t.initCause(zeusId);
            } else {
                t.getCause().initCause(zeusId);
            }
        }

        if (msg != null) {
            System.out.println("-------------------- filter thread name " + Thread.currentThread().getName());
        }
    }

    @PluginFactory
    public static CustomFilter createFilter(@PluginAttribute("onMatch") final Result match,
                                            @PluginAttribute("onMismatch") final Result mismatch) {
        return new CustomFilter();
    }
}